#include <IWeibo.hxx>
#include <IWeiboMethod.hxx>
#include <ParsingObject.hxx>
using namespace weibo;

#include "RtWeiboEngine.h"
#include "RtEnginePlatImpl.h"
#include "RtWeiboApp.h"
#include "RtEnv.h"
#include "RtWeiboCmd.h"
#include "RtDlgUtil.h"

CRtWeiboEngine* g_pWeiboEngine;
boost::shared_ptr<weibo::IWeibo> g_pWeiboPtr;

void OnDelegateCompleted(unsigned int methodOption, const char* httpHeader,ParsingObject* result, const UserTaskInfo* pTask);
void OnDelegateErrored(unsigned int methodOption, const int errCode, const int subErrCode,ParsingObject* result, const UserTaskInfo* pTask);
void OnDelegateWillRelease(unsigned int optionId, const weibo::UserTaskInfo* pTask);

CRtWeiboEngine::CRtWeiboEngine(void)
{
	g_pWeiboEngine=this;
	m_bLogin=false;

	g_pWeiboPtr=weibo::WeiboFactory::getWeibo();
	g_pWeiboPtr->startup();
}

CRtWeiboEngine::~CRtWeiboEngine(void)
{
	g_pWeiboEngine=NULL;

	g_pWeiboPtr->stopAll();
	g_pWeiboPtr->shutdown();
}

bool CRtWeiboEngine::AuthoriseValid()
{
	//todo access token can save, verify expire time
	return g_pWeiboEngine->m_bLogin;
}

void CRtWeiboEngine::Oauth2Web()
{
	CRtEnginePlatImpl* pImpl=(CRtEnginePlatImpl*)CRtWeiboApp::Static()->GetEngine();

#if 0
	CRtString strAppKey="1676133425";   //hmq
	CRtString strAppSecret="2ff229d17e54829d744f1ffa1904c3ef";
#else
	CRtString strAppKey="1864732384";	//cph
	CRtString strAppSecret="13bf6ffa0789600611d83c732ed5f52d";
#endif
	CRtString strRedirectUri="https://api.weibo.com/oauth2/default.html";

	char strReqAuth[256];
	sprintf(strReqAuth,"https://api.weibo.com/oauth2/authorize?client_id=%s&response_type=code&redirect_uri=%s",
		strAppKey.PtrZ(),strRedirectUri.PtrZ());
	CRtString strCode=pImpl->GetAuthCode(strReqAuth);
	if(strCode.Length()==0)
		return;

	weibo::IWeiboMethod* method = g_pWeiboPtr->getMethod();
	g_pWeiboPtr->setOption(weibo::WOPT_CONSUMER, strAppKey.PtrZ(), strAppSecret.PtrZ());
	method->oauth2web(strCode.PtrZ(),NULL);

	// Delegate option        
	g_pWeiboPtr->OnDelegateComplated = OnDelegateCompleted;        
	g_pWeiboPtr->OnDelegateErrored = OnDelegateErrored;        
	g_pWeiboPtr->OnDelegateWillRelease = OnDelegateWillRelease;
}

void CRtWeiboEngine::PostStatusesUpdate(const char* statusText,const CRespReceiver& rRespReceiver)
{
	weibo::IWeiboMethod* method = g_pWeiboPtr->getMethod();
	UserTaskInfo task;
	if(rRespReceiver.m_strAction.Length()>0)
		strcpy(task.mTaskId,rRespReceiver.m_strAction.PtrZ());
	task.mUsrData=rRespReceiver.m_pReceiver;
	method->postStatusesUpdate(statusText, NULL, &task);
}


char* CRtWeiboEngine::GetStatusesFriendTimeline(const CRespReceiver& rRespReceiver)
{
	weibo::IWeiboMethod* method = g_pWeiboPtr->getMethod();
	UserTaskInfo task;
	if(rRespReceiver.m_strAction.Length()>0)
	strcpy(task.mTaskId,rRespReceiver.m_strAction.PtrZ());
	task.mUsrData=rRespReceiver.m_pReceiver;
	char* fweibo=(char*)method->getStatusesFriendTimeline( NULL, &task);
	return fweibo;

}
void CRtWeiboEngine::ShowError(int error_code,const char* error)
{
	char* pBuf=new char[50+strlen(error)];
	sprintf(pBuf,"error code:%d\\n%s",error_code,error);

	CRtDlgUtil::ShowInfoDlg("Error",pBuf);
	delete pBuf;
}

void OnDelegateCompleted(unsigned int methodOption, const char* httpHeader,ParsingObject* result, const UserTaskInfo* pTask)
{        
	if (methodOption == WBOPT_OAUTH2_WEB_ACCESS_TOKEN)         
	{                
		if (result->isUseable())
		{                        
			//logined = true;                        
			std::string access_token = result->getSubStringByKey("access_token");
			std::string expires_in=result->getSubStringByKey("expires_in");

			g_pWeiboPtr->setOption(WOPT_ACCESS_TOKEN, access_token.c_str()); 

			g_pWeiboEngine->m_bLogin=true;
			g_pWeiboEngine->m_tAuthorizeTime.HomeTime();
			const char* str=expires_in.c_str();
			g_pWeiboEngine->m_nExpired = atoi(str);

			CRtString* pResp=new CRtString(result->getOriginString());
			CRtEnv::Static()->PostRtMessage(NULL,NULL,"",EWeiboRespMsg,methodOption,(uint)pResp);
		}        
	}        
	else //if (methodOption == WBOPT_POST_STATUSES_UPDATE)        
	{                
		if (result->isUseable())
		{
			CRtString* pResp=new CRtString(result->getOriginString());
			CRtEnv::Static()->PostRtMessage(NULL,(CRtEvtReceiver*)pTask->mUsrData,pTask->mTaskId,EWeiboRespMsg,methodOption,(uint)pResp);
		}
	}
}

void OnDelegateErrored(unsigned int methodOption, const int errCode, const int subErrCode,ParsingObject* result, const UserTaskInfo* pTask)
{        
	// Please reference http://open.weibo.com/wiki/Help/error        
	if (methodOption == WBOPT_OAUTH2_ACCESS_TOKEN)         
	{                
		if (result && result->isUseable())                
		{                        
			std::string error_code = result->getSubStringByKey("error_code");                        
			std::string request = result->getSubStringByKey("request");                        
			std::string error = result->getSubStringByKey("error");                
		}        
	}        
	else if (methodOption == WBOPT_POST_STATUSES_UPDATE)        
	{              
		if (result && result->isUseable())
		{
			std::string error_code = result->getSubStringByKey("error_code");                        
			std::string request = result->getSubStringByKey("request");                        
			std::string error = result->getSubStringByKey("error");

			//
			CRtString* pResp=new CRtString(result->getOriginString());
			CRtEnv::Static()->PostRtMessage(NULL,(CRtEvtReceiver*)pTask->mUsrData,pTask->mTaskId,EWeiboRespMsg,methodOption,(uint)pResp);
		}
	}
}

void OnDelegateWillRelease(unsigned int optionId, const weibo::UserTaskInfo* pTask)
{
	//DebugLog(<< __FUNCTION__ << "| Option Id: " << getOptionName(optionId));

	// Do noting!
}
